package com.zb.zeus.common.datasource.handler;

import com.baomidou.dynamic.datasource.toolkit.CryptoUtils;
import com.zb.zeus.common.core.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @author fujianjian
 * @date 2021/8/26 16:11
 **/
@Slf4j
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String.class)
public class SensitiveFieldTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, String s, JdbcType jdbcType) throws SQLException {
        String encrypt;
        try {
            encrypt = StringUtils.isNotEmpty(s) ? CryptoUtils.encrypt(s) : s;
        } catch (Exception e) {
            log.error("encrypt occur err, parameter:{}", s, e);
            encrypt = null;
        }
        preparedStatement.setString(i, encrypt);
    }


    @Override
    public String getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String encryptVal = resultSet.getString(s);
        String fatalVal;
        try {
            fatalVal = StringUtils.isNotEmpty(encryptVal) ? CryptoUtils.decrypt(encryptVal) : encryptVal;
        } catch (Exception e) {
            log.error("decrypt occur err, encrypt val:{}, column name:{}", encryptVal, s, e);
            fatalVal = null;
        }
        return fatalVal;
    }

    @Override
    public String getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String encryptVal = resultSet.getString(i);
        String fatalVal;
        try {
            fatalVal = StringUtils.isNotEmpty(encryptVal) ? CryptoUtils.decrypt(encryptVal) : encryptVal;
        } catch (Exception e) {
            log.error("decrypt occur err, encrypt val:{}, column index:{}", encryptVal, i, e);
            fatalVal = null;
        }
        return fatalVal;
    }

    @Override
    public String getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String encryptVal = callableStatement.getString(i);
        String fatalVal;
        try {
            fatalVal = StringUtils.isNotEmpty(encryptVal) ? CryptoUtils.decrypt(encryptVal) : encryptVal;
        } catch (Exception e) {
            log.error("decrypt occur err, encrypt val:{}, column index:{}", encryptVal, 1, e);
            fatalVal = null;
        }
        return fatalVal;
    }
}
